<script setup>
import EmojiPicker from 'vue3-emoji-picker'
import 'vue3-emoji-picker/css'
import { ref } from 'vue'
import { ClickOutside as vClickOutside } from 'element-plus'
import html2canvas from 'html2canvas'
import { useUserStore } from '../../stores'
import { io } from 'socket.io-client'
import { nextTick } from 'vue'

// import { ElMessage } from 'element-plus'
// import socket from '../../utils/socketio'
// import { onMounted, watch } from 'vue'
const userStore = useUserStore()
const { getUserListAction } = userStore
getUserListAction()

const getCurrentTime = () => {
  const now = new Date()
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

const message = ref([
  {
    id: 1,
    sender: 'me',
    content: '你好',
    time: getCurrentTime(),
    avatar: 'src/assets/img1.png',
    type: 'text'
  },
  {
    id: 2,
    sender: 'system',
    content: 'hh 进入了聊天室',
    time: getCurrentTime()
  },
  {
    id: 3,
    sender: 'other',
    content: '不好',
    time: getCurrentTime(),
    avatar: 'src/assets/img1.png',
    type: 'text'
  },
  {
    id: 4,
    sender: 'me',
    content: 'why',
    time: getCurrentTime(),
    avatar: 'src/assets/img1.png',
    type: 'text'
  },
  {
    id: 5,
    sender: 'system',
    content: 'hh 进入了聊天室',
    time: getCurrentTime()
  },
  {
    id: 6,
    sender: 'other',
    content: 'src/assets/img1.png',
    time: getCurrentTime(),
    avatar: 'src/assets/img1.png',
    type: 'image',
    filename: '',
    filesize: 0
  },
  {
    id: 7,
    sender: 'me',
    content: '',
    time: getCurrentTime(),
    avatar: 'src/assets/img1.png',
    type: 'file',
    filename: '简历.pdf',
    filesize: 23.45
  }
])
// console.log(message)

const socket = io('http://localhost:9000', {
  query: {
    page: 'chat',
    token: userStore.token
  }
})
socket.on('connect', () => {})

const userList = ref([])
socket.on('userList', (data) => {
  console.log(data)
  userList.value = data
})
const id = ref(8)
socket.on('join', (data) => {
  console.log(data)

  message.value.push({
    id: id.value,
    sender: 'system',
    content: `${data}`,
    time: getCurrentTime()
  })
  id.value++
})
socket.on('leave', (data) => {
  console.log(data)

  message.value.push({
    id: id.value,
    sender: 'system',
    content: `${data}`,
    time: getCurrentTime()
  })
  id.value++
})
// watch(() => {}, {})

const buttonRef = ref()
const popoverRef = ref()
const textarearef = ref()
const onClickOutside = () => {
  popoverRef.value?.hide()
}
function onSelectEmoji(emoji) {
  console.log(emoji)
  const text = textarearef.value
  // const text = document.querySelector('textarea')
  const startPos = text.selectionStart
  const endPos = text.selectionEnd
  const resulttext =
    text.value.substring(0, startPos) + emoji.i + text.value.substring(endPos)
  text.value = resulttext
  // console.log(text.value)
  popoverRef.value.hide()
  text.focus()
  text.selectionStart = startPos + emoji.i.length
  text.selectionEnd = endPos + emoji.i.length
  textarea.value = text.value
  // console.log(textarea.value)
}

const textarea = ref('')

// 使用padStart确保两位数格式

const mainref = ref()
const base64img = ref('')
const isShowCover = ref(false)
const captureChat = () => {
  // console.log(mainref.value.scrollHeight)
  const chatArea = document.getElementById('main')
  chatArea.style.height = chatArea.scrollHeight + 'px'
  return html2canvas(chatArea).then((canvas) => {
    chatArea.style.height = 'auto'
    const image = canvas.toDataURL('image/png')
    console.log(image)
    isShowCover.value = true
    base64img.value = image
    return image
  })
  // console.log(chatArea.scrollHeight)
}
const sendmessage = () => {
  console.log(textarea.value)
  socket.emit('sendmessage', {
    sender: 'me',
    content: textarea.value,
    username: userStore.currentUser.username.value
  })
  textarea.value = ''
}
socket.on('getmessage', (data) => {
  console.log(data)

  message.value.push({
    id: id.value,
    sender: data.sender,
    content: data.content,
    time: getCurrentTime(),
    avatar: data.avatar,
    type: data.type || 'text',
    filename: data.filename || '',
    filesize: data.filesize || 0
  })

  id.value++

  scrollToLatestMessage()
})
const getFileIcon = (filename) => {
  const ext = filename.split('.').pop().toLowerCase()
  const iconMap = {
    pdf: '📄',
    doc: ' 📝',
    docx: '📝',
    xls: '📊',
    xlsx: '📊',
    ppt: '📋',
    pptx: '📋',
    txt: '📄',
    zip: '📦',
    rar: '📦',
    '7z': '📦',
    mp4: '🎥',
    avi: '🎥',
    mov: '🎥',
    mp3: '🎵',
    wav: '🎵',
    flac: '🎵',
    exe: '⚙️',
    dmg: '⚙️',
    iso: '💿'
  }
  return iconMap[ext] || '📎'
}

// const fileInput = ref()

// const triggerInput = () => {
//   fileInput.value?.click()
// }
const onFileChange = (res, file) => {
  const filetype = file.raw.type.startsWith('image/') ? 'image' : 'file'
  const filename = file.raw.name
  socket.emit('sendmessage', {
    content: res.data.url,
    filesize: file.size,
    type: filetype,
    filename
  })
  // console.log(res.url)
  // console.log(res)
}
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const downloadFile = async (item) => {
  if (item.type === 'file') {
    try {
      const url = item.content.startsWith('/')
        ? 'http://localhost:9000' + item.content
        : item.content

      // 添加认证头
      const response = await fetch(
        url
        // {
        //   headers: {
        //     Authorization: `Bearer ${userStore.token}`
        //     // 或者根据你的认证方式调整
        //   }
        // }
      )

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const blob = await response.blob()
      const downloadUrl = URL.createObjectURL(blob)

      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = item.filename
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      setTimeout(() => URL.revokeObjectURL(downloadUrl), 1000)
    } catch (error) {
      console.error('下载失败:', error)
      alert('下载失败: ' + error.message)
    }
  }
}

const cutimage = ref()
const uploadCutImage = () => {
  // console.log(cutimage.value.src)
  socket.emit('sendmessage', { content: cutimage.value.src, type: 'image' })
  isShowCover.value = false
}
// 图片预览
const previewImage = (imageUrl) => {
  const newWindow = window.open()
  newWindow.document.write(`
    <html>
      <head><title>图片预览</title></head>
      <body style="margin:0; padding:20px; text-align:center; background:#f5f5f5;">
        <img src="${imageUrl}" style="max-width: 90%; max-height: 90%; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);" />
        <br><br>
        <button onclick="window.close()" style="padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">关闭</button>
      </body>
    </html>
  `)
}

const scrollToLatestMessage = () => {
  nextTick(() => {
    // 获取最后一条消息
    const lastMessage = message.value[message.value.length - 1]
    if (lastMessage) {
      const messageElement = document.getElementById(
        `message-${lastMessage.id}`
      )
      if (messageElement) {
        messageElement.scrollIntoView({
          behavior: 'smooth', // 平滑滚动
          block: 'end', // 垂直对齐到底部
          inline: 'nearest' // 水平对齐到最近位置
        })
      }
    }
  })
}
</script>

<template>
  <div>
    <el-container class="layout">
      <el-aside width="200px" class="aside">
        <div class="user" style="padding-left: 20px">
          <img :src="userStore.currentUser.useravatar" alt="" />
          <span>{{ userStore.currentUser.username }}</span>
        </div>
        <div class="userlist">
          <el-menu background-color="rgb(46, 52, 58)" text-color="#fff">
            <el-sub-menu index="1">
              <template #title>
                <span>用户列表</span>
              </template>
              <el-menu-item v-for="(item, index) in userList" :key="index">
                <div class="user">
                  <img :src="item.useravatar" alt="" />
                  <span>{{ item.username }}</span>
                </div>
              </el-menu-item>
              <!-- <el-menu-item index="1-2">
                <div class="user">
                  <img src="@/assets/img1.png" alt="" />
                  <span>哈哈</span>
                </div>
              </el-menu-item> -->
            </el-sub-menu>
          </el-menu>
        </div>
      </el-aside>
      <el-container class="right" style="background-color: rgb(236, 236, 236)">
        <el-header class="header">
          <div class="line">
            <span>聊天室(99)</span>
          </div>
        </el-header>
        <el-main ref="mainref" style="padding: 10px" id="main">
          <el-scrollbar>
            <div
              v-for="(item, index) in message"
              :key="index"
              :id="`message-${item.id}`"
            >
              <div
                v-if="['me', 'other'].find((i) => i === item.sender)"
                :class="['chat_message', item.sender]"
              >
                <!-- <div class="avatar"></div> -->
                <img class="avatar" :src="item.avatar" alt="" />
                <div class="bubble">
                  <div class="triangle"></div>
                  <div class="bubble_message">
                    <template v-if="item.type === 'image'">
                      <img
                        :src="item.content"
                        alt=""
                        style="max-width: 200px"
                        @dblclick="previewImage(item.content)"
                      />
                    </template>
                    <template v-else-if="item.type === 'file'">
                      <div class="file-message">
                        <div class="file-icon">
                          {{ getFileIcon(item.filename) }}
                        </div>
                        <div class="file-name">{{ item.filename }}&nbsp;</div>
                        <div class="file-size">
                          {{ formatFileSize(item.filesize) }}
                        </div>
                        <div class="file-download">
                          <el-button size="small" @click="downloadFile(item)">
                            下载
                          </el-button>
                        </div>
                      </div>
                    </template>
                    <template v-else>
                      {{ item.content }}
                    </template>
                  </div>
                  <div class="time">{{ item.time }}</div>
                </div>
              </div>
              <div v-else class="system">{{ item.content }}</div>
              <!-- <div class="system">哈哈&nbsp;&nbsp;进入了聊天室</div> -->
            </div>
          </el-scrollbar>
        </el-main>
        <el-footer class="footer">
          <div class="input">
            <div>
              <el-row style="cursor: pointer">
                <el-col
                  ref="buttonRef"
                  v-click-outside="onClickOutside"
                  :span="2"
                  >😃</el-col
                >
                <el-popover
                  width="300"
                  ref="popoverRef"
                  :virtual-ref="buttonRef"
                  trigger="click"
                  virtual-triggering
                >
                  <EmojiPicker :native="true" @select="onSelectEmoji" />
                </el-popover>

                <el-col :span="2">
                  <el-icon @click="captureChat"><Scissor /></el-icon>
                </el-col>
                <el-col :span="2">
                  <!-- <el-icon @click="triggerInput"><Folder /></el-icon> -->
                  <el-col :span="2">
                    <el-upload
                      action="http://localhost:9000/api/upload"
                      :show-file-list="false"
                      :on-success="onFileChange"
                    >
                      <el-icon><Folder /></el-icon>
                    </el-upload>
                  </el-col>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <textarea
                    v-model="textarea"
                    ref="textarearef"
                    @keydown.enter="sendmessage"
                    style="
                      width: 90%;
                      height: 80px;
                      border: none;
                      background-color: rgb(236, 236, 236);
                      outline: none;
                    "
                    name=""
                    id=""
                  ></textarea>
                </el-col>
              </el-row>
            </div>
            <div class="send">
              <span
                style="
                  font-size: 12px;
                  vertical-align: middle;
                  margin-right: 5px;
                  color: #999;
                "
                >按下Enter键发送</span
              >
              <el-button @click="sendmessage" size="small" style="width: 70px"
                >发送</el-button
              >
            </div>
          </div>
        </el-footer>
      </el-container>
    </el-container>
    <div class="cover" v-if="isShowCover">
      <img :src="base64img" ref="cutimage" alt="" />
      <div>
        <el-button @click="isShowCover = false"> 取消 </el-button>
        <el-button @click="uploadCutImage"> 将图片上传到聊天框 </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.layout {
  width: 700px;
  height: 500px;
  margin: 0 auto;
  margin-top: 50px;
  border: 1px solid #999;
  background-color: pink;
}
.layout .right {
  height: 100%;
}
.aside {
  display: flex;
  flex-direction: column;
  padding: 10px;
  color: white;
  background-color: rgb(46, 52, 58);
}

.user img {
  width: 30px;
  height: 30px;
  vertical-align: middle;
  margin-right: 10px;
}
.header {
  background-color: rgb(236, 236, 236);
  height: 50px;
}
.line {
  padding: 0 15px;
  height: 100%;
  border-bottom: 1px solid #999;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
}
.footer {
  height: 130px;
  border-top: 1px solid #999;
  display: flex;
  justify-content: center;
  align-items: center;
  /* padding: 10px 20px; */
}
::v-deep(.el-footer) {
  padding: 0;
}
.input {
  position: relative;
  width: 460px;
  height: 120px;
}
.textarea {
  border: none;
}
.send {
  position: absolute;
  bottom: 5px;
  right: 5px;
  /* width: 200px; */
  height: 20px;
}
.chat_message {
  display: flex;
  margin-bottom: 20px;
}
.me {
  flex-direction: row-reverse;
  justify-content: flex-start;
}

.other {
  flex-direction: row;
  justify-content: flex-start;
}
/* .chat_message .avatar {
  width: 30px;
  height: 30px;
  background: url('@/assets/img1.png') no-repeat center center/cover;
} */
.chat_message .avatar {
  width: 30px;
  height: 30px;
  object-fit: cover;
  /* border-radius: 50%; */
}
.chat_message .bubble {
  position: relative;
  /* margin-left: 10px; */
  padding: 5px;
  font-size: 14px;
  /* background-color: white; */
  border-radius: 3px;
  box-shadow: 0 0 3px 3px #e2dfdf;
}
.bubble .triangle {
  position: absolute;
  /* left: -8px; */
  top: 5px;
  width: 0px;
  height: 0px;
  border: 5px solid transparent;
  /* border-right: 5px solid white; */
}
.me .bubble {
  background-color: rgb(141, 221, 20);
  margin-right: 10px;
}
.me .bubble .triangle {
  right: -8px;
  border-left: 5px solid rgb(141, 221, 20);
}

.other .bubble {
  background-color: white;
  margin-left: 10px;
}
.other .bubble .triangle {
  left: -8px;
  border-left: 5px solid white;
}
.other .time {
  bottom: -15px;
  left: 0px;
}

.time {
  position: absolute;
  /* margin-left: 10px; */
  font-size: 12px;
  color: #999;
}
.me .time {
  bottom: -15px;
  right: 0px;
}
.cover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  /* background-color: rgb(196, 194, 194); */
  background-color: rgba(67, 66, 66, 0.6);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.cover img {
  width: 374px;
  height: 239px;
  margin-bottom: 10px;
}
.system {
  text-align: center;
  padding: 3px 0;
  font-size: 12px;
  color: #999;
}

/* 文件消息样式 */
.file-message {
  display: flex;
  align-items: center;
  padding: 8px;
  background: #f5f5f5;
  border-radius: 4px;
  min-width: 200px;
}

.file-icon {
  font-size: 24px;
  margin-right: 8px;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-weight: 500;
  color: #333;
  word-break: break-all;
  margin-bottom: 2px;
}

.file-size {
  font-size: 12px;
  color: #666;
}

.file-download {
  margin-left: 8px;
}

/* 下载功能 */
.download-link {
  display: none;
}
</style>
